<template>
  <div>
    <input ref="fileInputRef" type="file" class="n-file" :accept="props.accept" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
const fileInputRef = ref<HTMLInputElement | null>(null)
const props = defineProps({
  accept: {
    type: String,
    default: '',
  },
})
const cbRef = ref<((result: string) => void) | null>(null)
const choseFile = (cb: (result: string) => void): void => {
  fileInputRef.value?.click()
  cbRef.value = cb
}

onMounted(() => {
  fileInputRef.value?.addEventListener('change', (event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]
    if (file) {
      const reader = new FileReader()
      if (props.accept === 'image/*') {
        reader.addEventListener('load', (e) => {
          cbRef.value!(e.target!.result as string)
        })
        reader.readAsDataURL(file)
      } else {
        reader.addEventListener('load', (e) => {
          cbRef.value!(e.target!.result as string)
        })
        reader.readAsText(file)
      }
    }
    target.value = ''
  })
})

defineExpose({
  choseFile,
})
</script>

<style scoped>
.n-file {
  display: none;
}
</style>
